/*
 *  mmf.c
 *
 *  (C) 2011 Harry Wei
 */

#include <stdio.h>
#include <stdlib.h>
#include "mm.h"

/* init the stack with goods */
/*int init_stack(struct stack **top)*/
struct stack *init_stack(void)
{
	int i = 10;
	struct stack *goods = NULL;
	struct stack *follow = NULL;
	struct stack *top = NULL;

/*	srand(time(NULL));
	do {
		i = rand() % 11;
	} while (!i);*/
	top = (struct stack *)malloc(sizeof(struct stack));
	if (!top) {
		printf("Allocate Error!\n");
		return NULL;
	} else {
		goods = follow = top;
		while (i) {
			goods = (struct stack *)malloc(sizeof(struct stack));
			if (!goods) { 
				printf("Allocate Error!\n");
				return NULL;	/* a bug here */
			} else {
				goods->s_date = i;
				follow->next = goods;
				follow = goods;
				i = i - 1;
		//		printf("%d\n", goods->s_date);
			}
		}
		follow->next = NULL;
//		printf("%d\n", top->next->s_date);
	}
	return top;
}

/* add goods to queue for sorting */
int sort_goods(struct stack *top, struct queue *mer)
{
	int i = 5;	/* set the goods' amount */
	int temp;
	struct stack *take = top;
	struct queue *insert = NULL;

	srand(time(NULL));
	take = take->next;
	top = take;
	front = tail = mer = (struct queue *)malloc(sizeof(struct queue));
	if (!mer) {
		printf("Allocating Error!\n");
		return 1;
	}
	while (NULL != take) {
		tail = (struct queue *)malloc(sizeof(struct queue));
		if (!tail) {
			printf("Allocating Error!\n");
			return 1;
		}
		tail->q_date = take->s_date;
		mer->next = tail;
		mer = tail;
		take = take->next;
		free(top);
		top = take;
	}
	tail->next = NULL;
	mer = front;
	do { /* a bug here, i did not do queue feature */
		temp = rand() % 11;
		while (NULL != mer) {
			if (mer->next->q_date <= temp) {
				insert = (struct queue *)malloc(sizeof(struct queue));
				if (!insert) {
					printf("Allocating Error!\n");
					return 1;
				} else {
					insert->q_date = temp;
					insert->next = mer->next;
					mer->next = insert;
				}
			} else if (tail->q_date > temp) {
				insert = (struct queue *)malloc(sizeof(struct queue));
				if (!insert) {
					printf("Allocating Error!\n");
					return 1;
				} else {
					insert->q_date = temp;
					tail->next = insert;
					tail = insert;
					tail->next = NULL;
				}
			} else {
				mer = mer->next;
			}
		}
		i = i - 1;
	} while (i);
	return 0;
}

/* push all goods to stack */
int add_goods(struct stack *top)
{
	struct queue *f_queue = front->next;
	struct stack *estab = NULL;
	struct stack *follow = NULL;

	estab = follow = top = (struct stack *)malloc(sizeof(struct stack));
	if (!top) {
		printf("Allocating Error!\n");
		return 1;
	}
	front = f_queue;
	while (front) {
		estab = (struct stack *)malloc(sizeof(struct stack));
		if (!estab) {
			printf("Allocating Error!\n");
			return 1;
		}
		estab->s_date = front->q_date;
		front = front->next;
		free(f_queue);
		f_queue = front;
		follow->next = estab;
		follow = estab;
	}
	estab->next = NULL;
	return 0;
}
